package model

import (
	"gorm.io/gorm"
	"next-vue-backend/utils/errmsg"
	"time"
)

type Article struct {
	Category   Category `gorm:"foreignKey:CategoryId"`
	CreatedAt  time.Time
	UpdatedAt  time.Time
	Title      string `gorm:"type:varchar(100); not null" json:"title"`
	ArticleId  int    `gorm:"primary_key;auto_increment" json:"article_id"`
	CategoryId int    `gorm:"type:int; not null" json:"category_id"`
	Desc       string `gorm:"type:varchar(200); not null" json:"desc"`
	Content    string `gorm:"type:longtext" json:"content"`
	Img        string `gorm:"type:varchar(100)" json:"img"`
}

// CreateArticle 创建文章
func CreateArticle(data *Article) int {
	err := db.Create(&data).Error
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SSUCCESS
}

// GetCategoryAllArticle 查询所有分类下的文章
func GetCategoryAllArticle(id int, pageSize int, pageNum int) ([]Article, int, int64) {
	var cateArticleList []Article
	var total int64
	err = db.Preload("Category").Limit(pageSize).Offset((pageNum-1)*pageSize).Where("category_id = ?", id).Find(&cateArticleList).Count(&total).Error
	if err != nil {
		return nil, errmsg.ERROR_CATE_NOT_EXIST, 0
	}
	return cateArticleList, errmsg.SSUCCESS, total
}

// GetSingleArticleInfo 查询单篇文章
func GetSingleArticleInfo(id int) (Article, int) {
	article := Article{}
	category := Category{}
	err := db.Preload("Category").Where("article_id = ?", id).First(&article).Error
	// 通过Profile关联查询user数据, 查询结果保存到user变量
	db.Model(&article).Association("Category").Find(&category)
	if err != nil {
		return article, errmsg.ERROR_ARTICLE_NOT_EXIST
	}
	return article, errmsg.SSUCCESS
}

// GetArticle 查询文章列表
func GetArticle(pageSize int, pageNum int) ([]Article, int, int64) {
	var articleList []Article
	var total int64
	err = db.Preload("Category").Limit(pageSize).Offset((pageNum - 1) * pageSize).Find(&articleList).Count(&total).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, errmsg.ERROR, 0
	}
	return articleList, errmsg.SSUCCESS, total
}

// EditArticle 编辑文章
func EditArticle(id int, data *Article) int {
	var article Article
	var maps = make(map[string]interface{})
	maps["title"] = data.Title
	maps["category_id"] = data.CategoryId
	maps["desc"] = data.Desc
	maps["content"] = data.Content
	maps["img"] = data.Img
	err = db.Model(&article).Where("article_id = ?", id).Updates(maps).Error
	if err != nil {
		return errmsg.ERROR
	}

	return errmsg.SSUCCESS

}

// DeleteArticle 删除文章
func DeleteArticle(id int) int {
	var article Article
	err = db.Where("article_id = ? ", id).Delete(&article).Error
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SSUCCESS
}
